package com.hiwan.system.util;

import java.io.ByteArrayOutputStream;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import javax.crypto.Cipher;

public class PrivateKeyReader {
	
	private static String privateKey = "MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBAJG6HPFa4sk+HMqcWoVeFoPcvHJI3zF/7AzvcKAHMBzhMMssLE9dFTcJP7oTnJihS3ecaMrYQGpEOe44fs1FbYTYWJ66mv8i8YDJfzInXv9W7PzhsREQHalvJc6XM6MGEbBRg1htJ97R45jhkPIfGCbiqdfYiV43xxfBy9UD0czbAgMBAAECgYEAgkOi0aDTrt6l7/t581Pavn6XuXUohl/6SsnSnEowmPA3pLZU2ZC0gSD0ZUpYphswkbgv+Hr8gcGBI1A/EREpxsfJP35omdGxV6m5HgTyHD4jdLHpRJMITHh4YWiOYEOUFJ093hNner1cacFPjviKCJSKT+FZ7KxPTnT+tHcYpgkCQQDKZaTZGcB9yq60ypNh6wSGSF/v4JXtKoG4itY+QCV7nth5Td0j8dTMwnsxDdlMzJgCUnR2r6t9eyYRlW8RPDjlAkEAuFJJPB0ZdM1+nblGddnYTPruiqIZ+b4V0vZKyihrRUWnSz5cGfYufvuDQ5DHHP1CHxfYGBnZA/bH3yqAXmJSvwJBAMACD5J6MLfleTpAV/NzvrYZoRHzUKhPRAMrizZBKo4NUrY5nQpFmKir86zEw5ptGeRSDvStkRYYpzPVPSnvpNUCQQCyEbzyuGIpd4WFNsMdg9H1vM7LXAOgRMWsw4hJeXb4u2v9w0cTRcRxpOaRVcMm/HzusQhxcDc6HyXFMbhGdtLdAkEAlclouH4/fegiBTkfI1qFQmeMtnLf/9RLMGiaMlo5vbcLixDDJrWBOyxg0KJWvD80BwGKWUNz6Pqers+HudwAXg==";
	
	private static String RSA_JAVA = "RSA/ECB/PKCS1Padding";
	private static String RSA = "RSA";
	/** 
     * RSA最大解密密文大小 
     */  
    private static final int MAX_DECRYPT_BLOCK = 128;  
	
	public static PrivateKey get()throws Exception {
		 byte[] keyBytes = Base64.decode(privateKey.toCharArray());
         PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
         KeyFactory keyFactory = KeyFactory.getInstance(RSA);
         return keyFactory.generatePrivate(keySpec);
	}
	
	public static String decryptByPrivateKey(byte[] encryptedData)throws Exception {
		Cipher cipher = Cipher.getInstance(RSA_JAVA);
		RSAPrivateKey privKey = (RSAPrivateKey) PrivateKeyReader.get();
		cipher.init(Cipher.DECRYPT_MODE, privKey);
		int inputLen = encryptedData.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;  
		byte[] cache;  
		int i = 0;
		// 对数据分段解密  
		while (inputLen - offSet > 0) {  
			if (inputLen - offSet > MAX_DECRYPT_BLOCK) {  
				cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);  
			} else {  
				cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);  
			}  
			out.write(cache, 0, cache.length);  
			i++;  
			offSet = i * MAX_DECRYPT_BLOCK;  
		}  
		byte[] decryptedData = out.toByteArray();  
		out.close();  
		return new String(decryptedData);
	}
	
	public static void main(String[] args) throws Exception {
        String input = "000000";
        for(int i=0;i<5;i++){
        	String str = PublicKeyReader.encryptByPublicKey(input.getBytes());
            byte[] bb = Base64.decode(str.toCharArray());
            //加密后的东西
            System.out.println("cipher: " + str);        
            //开始解密
            System.out.println("plain : " + PrivateKeyReader.decryptByPrivateKey(bb));
        }
    }
	
}
